package com.raven.play.stream.test.alpakka;

import akka.Done;
import akka.actor.ActorSystem;
import akka.stream.Materializer;
import akka.stream.alpakka.slick.javadsl.Slick;
import akka.stream.alpakka.slick.javadsl.SlickSession;
import akka.stream.alpakka.slick.javadsl.SlickSession$;
import akka.stream.javadsl.Sink;
import akka.stream.javadsl.Source;
import com.raven.play.stream.test.BaseTest;
import org.junit.jupiter.api.Test;
// import slick.jdbc.H2Profile.api.*;

import java.util.Arrays;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

public class SlickExample extends BaseTest {

    @Test
    public void test1() {
        final ActorSystem system = ActorSystem.create("slick-example");
        final Materializer materializer = Materializer.createMaterializer(system);
        // final SlickSession session = SlickSession.forConfig("slick-h2"); // Configure H2 database in application.conf
        final SlickSession session = SlickSession$.MODULE$.forConfig("slick-h2"); // Configure H2 database in application.conf

        try {
            // Example data
            Source<String, ?> source = Source.from(Arrays.asList("Hello", "World"));
            Sink<String, CompletionStage<Done>> sink = Slick.sink(session, (Function<String, String>) s -> "INSERT INTO TEST_TABLE (DATA) VALUES ('" + s + "')");
            CompletionStage<Done> done = source.runWith(sink, materializer);

            // Wait for completion and shut down
            done.thenRun(() -> {
                System.out.println("Insertion done.");
                session.close();
                system.terminate();
            }).toCompletableFuture().get(10, TimeUnit.SECONDS);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
